package cn.ncupyh.comptest;
//冒泡排序
public class BubbleSort {
    public static void main(String[] args) {
        //给定一个整型数组, 实现冒泡排序(升序排序)
        int[] arr1 = {2,6,3,8,3,1};
//        bubbleSort(arr1);

        //给定一个整型数组, 判定数组是否有序（递增）
//        boolean b = ifArraySort(arr1);
//        System.out.println(b);

        //给定一个有序整型数组, 实现二分查找
        int downArray = binarySearch(arr1, 10);//返回下标
        System.out.println("下表为："+downArray);

//        //实现一个方法 copyOf, 对一个整型数组进行拷贝, 得到一个新的数组.
//        int[] ar2 = copyOf(arr1);
//        CalArraysAverage.printArray(ar2);
    }

    //数组的拷贝
    private static int[] copyOf(int[] arr1) {
        int[] arr2 = new int[arr1.length];
        for (int i = 0; i < arr1.length; i++) {
            arr2[i] = arr1[i];
        }
        return arr2;
    }

    //二分查找
    private static int binarySearch(int[] arr1,int n) {
        bubbleSort(arr1);//有序
        CalArraysAverage.printArray(arr1);
        //开始二分查找
        int left =0;
        int right = arr1.length-1;
        while (left<right){
            int z = (left+right)/2;
            if(arr1[left] == n){
                return left;
            }else if(arr1[right] == n){
                return right;
            }
            if(arr1[z] > n){
                right = z-1;
            }else if(arr1[z] < n){
                left = z + 1;
            }else return z;
        }
        return -1;
    }

    //给定一个整型数组, 判定数组是否有序（递增）
    private static boolean ifArraySort(int[] arr1) {
        int[] arr2 = arr1.clone();
        java.util.Arrays.sort(arr2);

        return java.util.Arrays.equals(arr1,arr2);
    }

    //给定一个整型数组, 实现冒泡排序(升序排序)
    private static void bubbleSort(int[] arr1) {
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr1.length-i-1; j++) {
                int m = arr1[j];
                int n = arr1[j+1];
                if(m > n){
                    int tmp = m;
                    arr1[j] = n;
                    arr1[j+1] = tmp;
                }
            }
        }
        CalArraysAverage.printArray(arr1);
    }
}
